package com.joker.airoleplayplatformback.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.joker.airoleplayplatformback.domain.po.AiAgentPO;
import com.joker.airoleplayplatformback.domain.po.ChatMessagePO;
import com.joker.airoleplayplatformback.domain.po.ChatSessionPO;
import com.joker.airoleplayplatformback.mapper.ChatMessageMapper;
import com.joker.airoleplayplatformback.mapper.ChatSessionMapper;
import com.joker.airoleplayplatformback.service.AiAgentService;
import com.joker.airoleplayplatformback.service.ChatService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;

/**
 * 聊天服务实现类
 * @author feixiang.li
 * @since 2025-09-27
 */
@Slf4j
@Service
public class ChatServiceImpl implements ChatService {

    @Autowired
    private ChatSessionMapper chatSessionMapper;

    @Autowired
    private ChatMessageMapper chatMessageMapper;

    @Autowired
    private AiAgentService aiAgentService;

    @Override
    @Transactional
    public ChatSessionPO createNewSession(Long userId, Long agentId) {
        AiAgentPO agent = aiAgentService.getAgentById(agentId);
        if (agent == null) {
            throw new RuntimeException("智能体不存在");
        }

        ChatSessionPO session = new ChatSessionPO();
        session.setSessionId(UUID.randomUUID().toString());
        session.setUserId(userId);
        session.setAgentId(agentId);
        session.setTitle("与" + agent.getName() + "的对话");
        session.setLastMessageTime(LocalDateTime.now());
        session.setMessageCount(0);
        session.setStatus(0);

        chatSessionMapper.insert(session);
        log.info("创建新会话: sessionId={}, userId={}, agentId={}", session.getSessionId(), userId, agentId);
        
        return session;
    }

    @Override
    public List<ChatSessionPO> getUserSessions(String userId) {
        LambdaQueryWrapper<ChatSessionPO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ChatSessionPO::getUserId, userId)
                   .eq(ChatSessionPO::getStatus, 0)
                   .orderByDesc(ChatSessionPO::getLastMessageTime);
        return chatSessionMapper.selectList(queryWrapper);
    }

    @Override
    public ChatSessionPO getSession(String sessionId) {
        LambdaQueryWrapper<ChatSessionPO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ChatSessionPO::getSessionId, sessionId);
        return chatSessionMapper.selectOne(queryWrapper);
    }

    @Override
    @Transactional
    public ChatMessagePO saveMessage(ChatMessagePO message) {
        chatMessageMapper.insert(message);
        
        // 更新会话的最后消息时间和消息数量
        updateSessionLastMessageTime(message.getSessionId());
        
        log.info("保存消息: messageId={}, sessionId={}, type={}", 
                message.getMessageId(), message.getSessionId(), message.getMessageType());
        
        return message;
    }

    @Override
    public List<ChatMessagePO> getSessionMessages(String sessionId) {
        LambdaQueryWrapper<ChatMessagePO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ChatMessagePO::getSessionId, sessionId)
                   .eq(ChatMessagePO::getStatus, 0)
                   .orderByAsc(ChatMessagePO::getCreateTime);
        return chatMessageMapper.selectList(queryWrapper);
    }

    @Override
    public List<ChatMessagePO> getRecentMessages(String sessionId, int limit) {
        LambdaQueryWrapper<ChatMessagePO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ChatMessagePO::getSessionId, sessionId)
                   .eq(ChatMessagePO::getStatus, 0)
                   .orderByDesc(ChatMessagePO::getCreateTime)
                   .last("LIMIT " + limit);
        
        List<ChatMessagePO> messages = chatMessageMapper.selectList(queryWrapper);
        // 反转列表，使其按时间正序排列
        java.util.Collections.reverse(messages);
        return messages;
    }

    @Override
    @Transactional
    public boolean deleteSession(String sessionId) {
        // 软删除会话
        LambdaUpdateWrapper<ChatSessionPO> sessionUpdateWrapper = new LambdaUpdateWrapper<>();
        sessionUpdateWrapper.eq(ChatSessionPO::getSessionId, sessionId)
                           .set(ChatSessionPO::getStatus, 1);
        
        // 软删除会话下的所有消息
        LambdaUpdateWrapper<ChatMessagePO> messageUpdateWrapper = new LambdaUpdateWrapper<>();
        messageUpdateWrapper.eq(ChatMessagePO::getSessionId, sessionId)
                           .set(ChatMessagePO::getStatus, 1);
        
        int sessionResult = chatSessionMapper.update(null, sessionUpdateWrapper);
        chatMessageMapper.update(null, messageUpdateWrapper);
        
        log.info("删除会话: sessionId={}, result={}", sessionId, sessionResult > 0);
        return sessionResult > 0;
    }

    @Override
    public boolean deleteMessage(String messageId) {
        LambdaUpdateWrapper<ChatMessagePO> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(ChatMessagePO::getMessageId, messageId)
                    .set(ChatMessagePO::getStatus, 1);
        
        int result = chatMessageMapper.update(null, updateWrapper);
        log.info("删除消息: messageId={}, result={}", messageId, result > 0);
        return result > 0;
    }

    @Override
    public void updateSessionLastMessageTime(String sessionId) {
        // 获取当前消息数量
        LambdaQueryWrapper<ChatMessagePO> countWrapper = new LambdaQueryWrapper<>();
        countWrapper.eq(ChatMessagePO::getSessionId, sessionId)
                   .eq(ChatMessagePO::getStatus, 0);
        long messageCount = chatMessageMapper.selectCount(countWrapper);

        // 更新会话信息
        LambdaUpdateWrapper<ChatSessionPO> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(ChatSessionPO::getSessionId, sessionId)
                    .set(ChatSessionPO::getLastMessageTime, LocalDateTime.now())
                    .set(ChatSessionPO::getMessageCount, messageCount);
        
        chatSessionMapper.update(null, updateWrapper);
    }
}
